package com.moke.xlsx
{
	import flash.utils.ByteArray;
	import flash.utils.Endian;

	/**
	 * 对Zip文件进行解码
	 * @author lipi
	 */
	public class XlsxFile
	{
		public static const sharedStringsURL:String = "xl/sharedStrings.xml";
		public static const workbookURL:String = "xl/workbook.xml";
		
		public static function getSheetURL(id:String):String
		{
			return "xl/worksheets/sheet" + id + ".xml";
		}
		
		//--------------------------------------------------------------
		// 
		//--------------------------------------------------------------
		
		private static const XML_TYPE:String = "xml";
		private static const SHEET_DIR_PREFIX:String = "xl/worksheets/sheet";
		
		private var _fileMap:Object = {};
		private var _fileInflateMark:Object = {};
			
		public function XlsxFile()
		{
			
		}
		
		public function dispose():void
		{
			_fileMap = null;
			_fileInflateMark = null;
		}
		
		public function set data(value:ByteArray):void
		{
			if(value != null)
			{
				value.endian = Endian.LITTLE_ENDIAN;
				value.position = 0;
				reset();
				parseFile(value);
			}
		}
		
		private function reset():void
		{
			_fileMap = {};
			_fileInflateMark = {};
		}
		
		private function parseFile(data:ByteArray):void
		{
			while (true)
			{
				var headValue:int = data.readUnsignedInt();
				if (headValue != 0x04034b50)
				{
					break;
				}
				data.position = data.position + 14;
				var compressSize:int = data.readUnsignedInt();
				var uncompressSize:int = data.readUnsignedInt();
				var fileNameLength:int = data.readUnsignedShort();
				var otherLength:int = data.readUnsignedShort();
				var fileName:String = data.readUTFBytes(fileNameLength);
				data.position = data.position + otherLength;
				var bytes:ByteArray = new ByteArray();
				data.readBytes(bytes, 0, compressSize);
				_fileMap[fileName] = bytes;
			}
		}

		/**
		 * 通过文件名取得解压缩后的文件的二进制数据
		 * @param fileName 文件名
		 * @return 文件的二进制数据
		 */
		public function getFile(fileName:String):ByteArray
		{
			var bytes:ByteArray = _fileMap[fileName];
			if (_fileInflateMark[fileName] != true)
			{
				bytes.position = 0;
				bytes.inflate();
				_fileInflateMark[fileName] = true;
			}
			return bytes;
		}

		/**
		 * 取得zip中的文件名的列表
		 * @return
		 *
		 */
		public function getFileNameList():Array
		{
			var fileNames:Array = [];
			for (var name:String in _fileMap)
			{
				fileNames.push(name);
			}
			return fileNames;
		}
	}
}